import React, { useRef, useState } from 'react'
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog
} from 'antd-mobile'
import classNames from 'classnames'
import styles from './index.module.scss'
import {
  getUserProfile,
  updateUserProfile,
  updateUserPhoto
} from '@/store/actions/profile'
import useInitialState from '@/hooks/useInitialState'
import EditInput from './EditInput/EditInput'
import EditList from './EditList/EditList'
import { useDispatch } from 'react-redux'
import { AxiosError } from 'axios'
import dayjs from 'dayjs'
import { logout } from '@/store/actions/login'
import { useHistory } from 'react-router'

const Item = List.Item
type showInput = {
  type: '' | 'name' | 'intro'
  show: boolean
}
type showList = {
  type: '' | 'photo' | 'gender'
  show: boolean
}

const ProfileEdit = () => {
  const dispatch = useDispatch()
  const { userProfile } = useInitialState(getUserProfile, 'profile')
  // 昵称和简介修改弹层
  const [showInput, setShowInput] = useState<showInput>({
    type: '',
    show: false
  })
  // 关闭修改昵称和简介的弹层
  const hideinput = () => {
    setShowInput({ type: '', show: false })
  }
  // 修改子组件内的昵称,简介或性别
  const fileRef = useRef<HTMLInputElement>(null)
  const onUpdate = async (key: string, value: string) => {
    try {
      console.log(key, 11111, value)
      // 修改图片
      if (key === 'photo') {
        fileRef.current!.click()
        return
      }
      await dispatch(updateUserProfile(key, value))
      Toast.show({
        content: '修改成功!'
      })
      hideinput()
      hideList()
    } catch (e) {
      // 类型断言
      const error = e as AxiosError<{ message: string }>
      let content = '错误'
      if (error.response) {
        content = error.response.data.message
      }
      Toast.show({
        content: content
      })
    }
  }
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0]
    if (!file) return
    // FormData 用来做文件上传的
    const photoData = new FormData()
    photoData.append('photo', file)
    await dispatch(updateUserPhoto(photoData))
    Toast.show({
      content: '修改成功!'
    })
    hideList()
  }

  // 头像和性别修改弹层
  const [showList, setShowList] = useState<showList>({
    type: '',
    show: false
  })
  // 关闭修改头像和性别的弹层
  const hideList = () => {
    setShowList({ type: '', show: false })
  }
  // 修改生日
  const [showBirthday, setShowBirthday] = useState(false)
  // 退出
  const history = useHistory()

  return (
    <div className={styles.root}>
      <div className="content">
        <input type="file" ref={fileRef} hidden onChange={onChangePhoto} />
        {/* 标题 */}
        <NavBar
          onBack={() => {
            history.replace('/home/profile')
          }}
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}>
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              onClick={() => setShowList({ type: 'photo', show: true })}
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={userProfile.photo} alt="" />
                </span>
              }
              arrow>
              头像
            </Item>
            <Item
              onClick={() => setShowInput({ type: 'name', show: true })}
              arrow
              extra={userProfile.name}>
              昵称
            </Item>
            <Item
              onClick={() => setShowInput({ type: 'intro', show: true })}
              arrow
              extra={
                <span
                  className={classNames(
                    'intro',
                    userProfile.intro && 'normal'
                  )}>
                  {userProfile.intro || '未填写'}
                </span>
              }>
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              onClick={() => setShowList({ type: 'gender', show: true })}
              arrow
              extra={userProfile.gender === 0 ? '男' : '女'}>
              性别
            </Item>
            <Item
              onClick={() => setShowBirthday(true)}
              arrow
              extra={userProfile.birthday}>
              生日
            </Item>
          </List>
        </div>

        <div className="logout">
          <Button
            className="btn"
            onClick={() => {
              const handler = Dialog.show({
                title: '傻小子!!!',
                content: '你确定退出吗？',
                closeOnAction: true,
                actions: [
                  [
                    {
                      key: 'cancel',
                      text: '取消',
                      onClick: () => {
                        handler.close()
                      }
                    },
                    {
                      key: 'confirm',
                      text: '确认',
                      onClick: () => {
                        dispatch(logout())
                        history.replace('/login')
                        Toast.show({ content: '退出成功' })
                      },
                      style: {
                        color: 'var(--adm-color-weak)'
                      }
                    }
                  ]
                ]
              })
            }}>
            退出登录
          </Button>
        </div>
      </div>

      {/* 修改名字和简介;destroyOnClose 可以保证关闭弹层时销毁组件 */}
      <Popup visible={showInput.show} position="right" destroyOnClose>
        <div style={{ width: '100vw', height: '100%' }}>
          <EditInput
            onUpdate={onUpdate}
            type={showInput.type}
            hideinput={hideinput}
          />
        </div>
      </Popup>
      <Popup visible={showList.show} position="bottom">
        {/* <div style={{ width: '100vw', height: '100%' }}> */}
        <EditList
          onUpdate={onUpdate}
          type={showList.type}
          hideList={hideList}
        />
        {/* </div> */}
      </Popup>
      <DatePicker
        visible={showBirthday} //  显示，隐藏
        value={new Date(userProfile.birthday)} // 当前选中的值
        onCancel={() => {
          setShowBirthday(false)
        }} // 取消事件
        onConfirm={(value) => {
          console.log(value, 123456)
          const birthday = dayjs(value).format('YYYY-MM-DD')
          onUpdate('birthday', birthday)
          setShowBirthday(false)
        }} // 点击确认
        title="选择年月日" // 标题
        min={new Date('1900-01-01')} // 最小日期
        max={new Date()} // 最大日期
      />
    </div>
  )
}

export default ProfileEdit
